#include <stdio.h>
#include <dirent.h>
#include <unistd.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "server.h"

int rdfd, wrfd;

void create_pipes() {
    /* Create the first named - pipe */
    if ((mkfifo(NP_READ, 0666) == -1) && (errno != EEXIST)) {
        perror("Error creating the named pipe");
        exit(1);
    }

    if ((mkfifo(NP_WRITE, 0666) == -1) && (errno != EEXIST)) {
        perror("Error creating the named pipe");
        exit(1);
    }
    /* Open the first named pipe for reading */
    rdfd = open(NP_READ, O_RDONLY);
    /* Open the second named pipe for writing */
    wrfd = open(NP_WRITE, O_WRONLY);
}

int main(int argc, char *argv[]) {
    if (read_conf() == ERROR) {
        perror("No se ha podido leer el archivo de configuración del Servidor. Se aborta la operación.\n");
        exit(1);
    };
    create_pipes();

    PACKAGE *package = malloc(sizeof (PACKAGE));

    while (1) {
        /* Read from the first pipe */
        read(rdfd, package, sizeof (PACKAGE));

        switch (package->op) {
            case RLS:
                rls(package);
                break;
            case RCD:
                rcd(package);
                break;
            case GET:
                get(package);
                break;
            case PUT:
                put(package);
                break;
            default:
                exit(0);
        }
    }
}
